package com.apkfuns.jsbridge;


import com.apkfuns.jsbridge.common.IWebView;
import com.apkfuns.jsbridge.module.JBCallback;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.TextTool;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import org.jetbrains.annotations.NotNull;

/**
 * Created by pengwei on 16/5/6.
 */
final class JBCallbackImpl implements JBCallback {

    private String name;
    private JsMethod method;
    private EventHandler mHandler;

    JBCallbackImpl(@NotNull JsMethod method, @NotNull String name) {
        this.method = method;
        this.name = name;
        mHandler = new EventHandler(EventRunner.getMainEventRunner());
    }

    @Override
    public void apply(Object... args) {
        if (method == null || method.getModule() == null || method.getModule().mWebView == null
                || TextTool.isNullOrEmpty(name)) {
            return;
        }
        String callback = method.getCallback();
        final StringBuilder builder = new StringBuilder("javascript:");
        builder.append("if(" + callback + " && " + callback + "['" + name + "']){");
        builder.append("var callback = " + callback + "['" + name + "'];");
        builder.append("if (typeof callback === 'function'){callback(");
        if (args != null && args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                builder.append(JBUtils.toJsObject(args[i]));
                if (i != args.length - 1) {
                    builder.append(",");
                }
            }
        }
        builder.append(")}else{console.error(callback + ' is not a function')}}");
        LogUtils.info("JBCallbackImpl","JACK evaluateJavascript2 " + builder.toString());
        mHandler.sendEvent(InnerEvent.get(new Runnable() {
            @Override
            public void run() {
                if (method.getModule().mWebView instanceof WebView) {
                    ((WebView) method.getModule().mWebView).load(builder.toString());
                } else if (method.getModule().mWebView instanceof IWebView) {
                    ((IWebView) method.getModule().mWebView).loadUrl(builder.toString());
                }
            }
        }));
    }

}
